import type { Settings as LayoutSettings } from '@ant-design/pro-layout';
import type { RunTimeLayoutConfig } from 'umi';
import { history } from 'umi';
import RightContent from '@/components/RightContent';
import React from 'react';
import {getCurrentUser, recordIp} from "@/pages/user/Login/service";
import {DefaultFooter} from "@ant-design/pro-layout";
import {getMenu} from "@/services/ant-design-pro/api";
import {MenuDataItem} from "@umijs/route-utils";
import {notification} from "antd";


const loginPath = '/user/login';

/** 获取用户信息比较慢的时候会展示一个 loading */
// export const initialStateConfig = {
//   loading: <PageLoading />,
// };

/**
 * @see  https://umijs.org/zh-CN/plugins/plugin-initial-state
 * */
export async function getInitialState(): Promise<{
  settings?: Partial<LayoutSettings>;
  currentUser?: API.CurrentUser;
  menuData?: MenuDataItem[] | undefined;
  fetchUserInfo?: () => Promise<API.CurrentUser | undefined>;
}> {
  const fetchUserInfo = async () => {
    //判断是否为pc端
    let flag = /(Win32|Win16|WinCE|Mac68K|MacIntel|MacIntel|MacPPC|Linux mips64)/i.test(navigator.platform);
    if (!flag) {
      notification.info({
        message: '为了更好的使用体验，请使用电脑浏览器访问哦。◕ᴗ◕。',
      });
    }
    const res = await getCurrentUser();
    if (res.status == 200){
      let user = res.data;
      window.permissions = user.permissionList.split(',');
      window.top.user = res.data;
      return user;
    }else {
      history.push(loginPath);
      await recordIp();
      return undefined;
    }
  };

  if (history.location.pathname !== loginPath) {
    const currentUser = await fetchUserInfo();
    let menuData = await getMenu().then(res => res);
    menuData = fixMenuItemIcon(menuData);
    return {
      fetchUserInfo,
      currentUser,
      menuData,
      settings: {},
    };
  }
  return {
    fetchUserInfo,
    settings: {},
  };
}

const MyIcon = (item: MenuDataItem) => {
  return (
    <span className='anticon font'>
      <span className={`iconfont ${item.icon}`}></span>
    </span>
  )
};

const fixMenuItemIcon = (menus: MenuDataItem[]): MenuDataItem[] => {
  menus.forEach((item) => {
    const {icon, children} = item;
    if (typeof icon === 'string') {
      item.icon = <MyIcon icon={icon}/>;
    }
    children && children.length > 0 ? item.children = fixMenuItemIcon(children) : null
  });
  return menus
};


const police = require('../public/policeLogo.png');

// ProLayout 支持的api https://procomponents.ant.design/components/layout
export const layout: RunTimeLayoutConfig = ({ initialState } : {settings?: LayoutSettings; currentUser?: API.CurrentUser, menuData: MenuDataItem[]}) => {
  return {
    menuDataRender: () => { return !initialState?.menuData ? [] : initialState.menuData},
    rightContentRender: () => <RightContent/>,
    disableContentMargin: false,
    //水印配置
    // waterMarkProps: {
    //   content: initialState?.currentUser?.loginName,
    // },
    onPageChange: () => {
      const { location } = history;
      // 如果没有登录，重定向到 login
      if (!initialState?.currentUser?.id && location.pathname !== '/user/login') {
        getCurrentUser();
        history.push('/user/login');
      }
    },
    footerRender: () => (
    <DefaultFooter
      links={[
        { key: '', title: <span><img src={police}/>鄂公网安备 42068302000301号</span>,
          href: 'https://www.beian.gov.cn/portal/registerSystemInfo?recordcode=42068302000301', blankTarget: true},
        { key: '', title: '鄂ICP备2022006469号', href: 'https://beian.miit.gov.cn/', blankTarget: true }
      ]}
      copyright='2022 jokerpan.xyz 版权所有'
    />
    ),
    ...initialState?.settings,
  };
}
